package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.mapper.ItemDescMapper;
import com.chen.mapper.ItemMapper;
import com.chen.pojo.Item;
import com.chen.pojo.ItemDesc;
import com.chen.service.ItemService;

import com.chen.vo.EasyUITable;
import com.chen.vo.EasyUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public EasyUITable findItemByPage(int page, int rows) {
        IPage mpPage = new Page(page, rows);
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("updated");
        mpPage = itemMapper.selectPage(mpPage, queryWrapper);
        long total = mpPage.getTotal();    //获取记录总数
        List<Item> itemList = mpPage.getRecords();    //获取查询当前页
        return new EasyUITable(total, itemList);
    }

    @Override
    @Transactional //开启事务
    public void saveItem(Item item, ItemDesc itemDesc) {
        item.setStatus(1);
        itemMapper.insert(item);
        // 获取主键信息
        itemDesc.setItemId(item.getId());
        itemDescMapper.insert(itemDesc);

    }

    @Override
    @Transactional
    public void updateItem(Item item, ItemDesc itemDesc) {
        itemMapper.updateById(item);
        // 补全商品详情数据
        itemDesc.setItemId(item.getId());
        itemDescMapper.updateById(itemDesc);
    }

    @Override
    public void deleteItems(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        itemMapper.deleteBatchIds(idList);
    }

    @Override
    public void updateStatus(Long[] ids, Integer status) {
        Item item = new Item();
        item.setStatus(status);
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        itemMapper.update(item, queryWrapper);
    }

    @Override
    public ItemDesc findItemDescById(Long itemId) {
        return itemDescMapper.selectById(itemId);
    }




}
